<?php

namespace app\admin\controller;

use think\Request;
use app\common\server\Code;
use app\common\server\TreeData;
use app\common\model\Category as CatModel;

class Category extends Base
{
    public function lst(Request $request){
        $list = CatModel::getList()->toArray();
        $list=TreeData::tree($list,'cat_name');
        $this->assign("list",$list);
        return $this->fetch();
    }

    public function add(Request $request,$pid="")
    {
        try{
            if($request->isPost()){
                $params = $request->post();
                $validateResult=$this->validateData('category','add');
                if($validateResult!==true) return apiReturn(Code::$error,$validateResult);
                $result = CatModel::create($params);
                if($result) return apiReturn();
                return apiReturn(Code::$error);
            }else{
                if(empty((int)$pid)){
                    $list = CatModel::getList()->toArray();
                    $list=TreeData::tree($list,'cat_name');
                    $this->assign("list",$list);
                }else{
                    $this->assign("pid",$pid);
                }
                return $this->fetch();
            }
        }catch (\Exception $e){
            return apiReturn(Code::$error,$e->getMessage());
        }
    }

    public function edit(Request $request,$id)
    {
        if($request->isPost()){
            $params = $request->post();
            $validateResult=$this->validateData('category','edit');
            if($validateResult!==true) return apiReturn(Code::$error,$validateResult);
            $save_data = [
                'cat_name' => $params['cat_name'],
                'desc'=>$params['desc'],
                'sort' => $params['sort'],
            ];
            $result=$admin = CatModel::where('id',$id)->update($save_data);
            if($result) return apiReturn();
            return apiReturn(Code::$error);
        }else{
            $info = CatModel::get($id);
            $this->assign("info",$info);
            return $this->fetch();
        }
    }

    public function delete($id)
    {
        //节点还有子节点
        if(CatModel::hasChild($id)) return apiReturn(Code::$error,"分类下还有子分类！！！");
        $result=CatModel::destroy($id);
        if($result) return apiReturn();
        return apiReturn(Code::$error);
    }
}
